/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/2
 */


// import Mock from 'mockjs';
import { mockAPIPrefix } from '../src/config';
import jwt from 'jsonwebtoken';

// let usersListData = Mock.mock({
//   'data|80-100': [
//     {
//       id: '@id',
//       name: '@name',
//       nickName: '@last',
//       phone: /^1[34578]\d{9}$/,
//       'age|11-99': 1,
//       address: '@county(true)',
//       isMale: '@boolean',
//       email: '@email',
//       createTime: '@datetime',
//       avatar () {
//         return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1));
//       },
//     },
//   ],
// });

function getAccessTokenStringFromReq (req) {
  return req.headers['Unite-Access-Token']
    || req.headers['unite-access-token']
    || req.query.accessToken;
}

// let database = usersListData.data;

const EnumRoleType = {
  ADMIN: 'admin',
  DEFAULT: 'guest',
  DEVELOPER: 'developer',
};

const userPermission = {
  DEFAULT: {
    visit: ['1', '2', '21', '7', '5', '51', '52', '53'],
    role: EnumRoleType.DEFAULT,
  },
  ADMIN: {
    role: EnumRoleType.ADMIN,
  },
  DEVELOPER: {
    role: EnumRoleType.DEVELOPER,
  },
};

const adminUsers = [
  {
    id: 0,
    username: 'admin',
    password: 'admin',
    permissions: userPermission.ADMIN,
  }, {
    id: 1,
    username: 'guest',
    password: 'guest',
    permissions: userPermission.DEFAULT,
  }, {
    id: 2,
    username: '吴彦祖',
    password: '123456',
    permissions: userPermission.DEVELOPER,
  },
];

// const queryArray = (array, key, keyAlias = 'key') => {
//   if (!(array instanceof Array)) {
//     return null;
//   }
//   let data;
//
//   for (let item of array) {
//     if (item[keyAlias] === key) {
//       data = item;
//       break;
//     }
//   }
//
//   if (data) {
//     return data;
//   }
//   return null;
// };
//
// const NOTFOUND = {
//   message: 'Not Found ~~',
//   documentation_url: 'http://localhost:8000/request',
// };

const generateAccessToken = ({ iss, userID }) => {
  return jwt.sign({
    userID,
  }, 'secret', {
    algorithm: 'HS256',
    issuer: iss,
    expiresIn: 7 * 24 * 3600,
  });
};

const getToken = (accessTokenStr) => {
  const verifyRes = jwt.verify(accessTokenStr, 'secret', {
    algorithms: 'HS256',
  });

  if (!verifyRes) {
    return null;
  }

  return jwt.decode(accessTokenStr);
};

export default {

  [`POST ${mockAPIPrefix}/auth/login`] (req, res) {
    const { username, password } = req.body;
    const user = adminUsers.filter(item => item.username === username);

    if (user.length > 0 && user[0].password === password) {
      const currentUser = user[0];

      // Generate access token
      const accessToken = generateAccessToken({ iss: `${currentUser.id}_${Date.now()}`, userID: currentUser.id });

      res.json({
        success: true,
        message: 'Ok',
        accessToken,
      });
    } else {
      res.status(400).end();
    }
  },

  [`POST ${mockAPIPrefix}/auth/logout`] (req, res) {
    const accessToken = getAccessTokenStringFromReq(req);
    if (!accessToken) {
      res.status(200).send({ message: 'Not Login' });
      return;
    }

    const token = getToken(accessToken);
    const response = {};
    if (!token) {
      res.status(200).send({ message: 'Not Login' });
      return;
    }
    response.success = true;
    response.message = '注销成功';
    res.json(response);
  },

  // get user api
  [`GET ${mockAPIPrefix}/user`] (req, res) {
    const accessToken = getAccessTokenStringFromReq(req);
    if (!accessToken) {
      res.status(200).send({ message: 'Not Login' });
      return;
    }
    const token = getToken(accessToken);
    const response = {};
    const user = {};
    if (!token) {
      res.status(200).send({ message: 'Not Login' });
      return;
    }
    const userItem = adminUsers.filter(_ => _.id === token.payload.userID);
    if (userItem.length > 0) {
      user.permissions = userItem[0].permissions;
      user.username = userItem[0].username;
      user.id = userItem[0].id;
    }
    response.success = true;
    response.user = user;
    res.json(response);
  },
};
